import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { ReuseTabService } from '@delon/abc';
import { ApiService } from '@core/api.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { observable, forkJoin } from 'rxjs';
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { DatePipe } from '@angular/common';
import { StatusFollowService } from '@core/statusFollow.service';
import { environment } from '../../../../environments/environment';
import { MessageListenerTools } from '@core/messageListener.tool';
import { TreeTools } from '@core/treeTools.tool';
import { ExportFileService } from '@core/exportFile';

const responseHeaders = new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8');
@Component({
  selector: 'app-workorderpreparation',
  templateUrl: './workorderpreparation.component.html',
  styleUrls: ['./workorderpreparation.component.less']
})
export class workorderpreparationComponent implements OnInit {
  examData: any = [];
  pageValue = '50';
  selectedValue = '50';
  rowPage = 1;
  pageIndex = 1;
  zyrqValue1 = this.datePipe.transform(new Date().getTime() - 86400000, 'yyyy-MM-dd');
  zyrqValue2 = this.datePipe.transform(new Date().getTime() + 86400000, 'yyyy-MM-dd');
  rowTotal = 0;
  pageTotal = '';
  displayData = [];
  devforsele = [];
  allChecked = false;
  checkIndexes = new Set(); // 存储被勾选的实际序号
  indeterminate = false;
  dataviewVisible = false;
  // devviewVisible = false;
  dataviewTabs = ['维修日计划信息'];
  lockHeadScroll = { x: '4200px', y: window.innerHeight - 360 + 'px' };
  addData: any = [];
  pagetype = 'cjbz';
  // temp data
  // orgselectedList: any = [];
  // staselectedList: any = [];
  zorronigebiaozi = true;
  // peopleList = [];
  mainRow: any = {}; // 弹窗页面中的主表选中条目数据
  tabCmpData: any = [];
  tabActiveIndex = 0;
  // showSubmit = true;
  editable = true;
  listOfTagOptions = [];
  dropdownStyle = {
    height: '200px',
  };
  swfwy_isNormal = [];
  queryParam: any = {};
  tabsVisiable = [true];
  treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
  fieldTrans_up2low = {
    N_ID: 'nnId',
    VC_ORG$ID: 'vcOrgId',
    VC_STA: 'vcSta',
    VC_EQU$TYPE: 'vcEquType',
    VC_EQU$CLASS: 'vcEquClass',
    VC_DEV$ID: 'vcDevId',
    VC_DEV$NAME: 'vcDevName',
    VC_GROUP: 'vcGroup',
    VC_IN$SAFER: 'vcInSafer',
    VC_OUT$SAFER: 'vcOutSafer',
    VC_TEAMMEN: 'vcTeammen',
    VC_WORKORDER: 'vcWorkorder',
    VC_TOOL: 'vcTool',
    VC_INOUTTYPE: 'vcInouttype',
    VC_KTREQUIRE: 'vcKtrequire',
    VC_RISK$CONTROL: 'vcRiskControl',
    VC_DINGKONG$REQUIRE: 'vcDingkongRequire',
    VC_TYPE: 'vcType',
    VC_PROJECT: 'vcProject',
    VC_WORK$PLACE: 'vcWorkPlace',
    VC_NEED$SKYWIN: 'vcNeedSkywin',
    VC_STATUS: 'vcStatus',
    N_PLAN$NUM: 'nPlanNum',
    VC_LEVEL: 'vcLevel',
    VC_ORDER: 'vcOrder',
    DT_WORK$DAY: 'dtWorkDay',
    VC_WA$PERSON: 'vcWaPerson',
    VC_SKYWIN$TYPE: 'vcSkywinType',
    VC_SKYWIN$STIME: 'vcSkywinStime',
    VC_SKYWIN$ETIME: 'vcSkywinEtime',
    VC_DEL: 'vcDel',
    VC_NEED$ROAD: 'vcNeedRoad',
    VC_SG$ID: 'vcSgId',
  };
  fieldTrans_low2up = {
    nnId: 'N_ID',
    vcOrgId: 'VC_ORG$ID',
    vcSta: 'VC_STA',
    vcEquType: 'VC_EQU$TYPE',
    vcEquClass: 'VC_EQU$CLASS',
    vcDevId: 'VC_DEV$ID',
    vcDevName: 'VC_DEV$NAME',
    vcGroup: 'VC_GROUP',
    vcInSafer: 'VC_IN$SAFER',
    vcOutSafer: 'VC_OUT$SAFER',
    vcTeammen: 'VC_TEAMMEN',
    vcWorkorder: 'VC_WORKORDER',
    vcTool: 'VC_TOOL',
    vcInouttype: 'VC_INOUTTYPE',
    vcKtrequire: 'VC_KTREQUIRE',
    vcRiskControl: 'VC_RISK$CONTROL',
    vcDingkongRequire: 'VC_DINGKONG$REQUIRE',
    vcType: 'VC_TYPE',
    vcProject: 'VC_PROJECT',
    vcWorkPlace: 'VC_WORK$PLACE',
    vcNeedSkywin: 'VC_NEED$SKYWIN',
    vcStatus: 'VC_STATUS',
    nPlanNum: 'N_PLAN$NUM',
    vcLevel: 'VC_LEVEL',
    vcOrder: 'VC_ORDER',
    dtWorkDay: 'DT_WORK$DAY',
    vcWaPerson: 'VC_WA$PERSON',
    vcSkywinType: 'VC_SKYWIN$TYPE',
    vcSkywinStime: 'VC_SKYWIN$STIME',
    vcSkywinEtime: 'VC_SKYWIN$ETIME',
    vcDel: 'VC_DEL',
    vcNeedRoad: 'VC_NEED$ROAD',
    vcSgId: 'VC_SG$ID',
  };

  fieldTrans_up2low_xj = {
    N_ID: 'nnId',
    VC_WORK$STIME: 'vcWorkStime',
    VC_WORK$ETIME: 'vcWorkEtime',
    VC_FINISHEDORNOT: 'vcFinishedornot',
    VC_FINISHED: 'vcFinished',
    VC_UNFI$REASON: 'vcUnfiReason',
  };

  fieldTrans_low2up_xj = {
    nnId: 'N_ID',
    vcWorkStime: 'VC_WORK$STIME',
    vcWorkEtime: 'VC_WORK$ETIME',
    vcFinishedornot: 'VC_FINISHEDORNOT',
    vcFinished: 'VC_FINISHED',
    vcUnfiReason: 'VC_UNFI$REASON',
  };

  lastPeopleNode: any;
  // nzNoResult = '该日期范围内没有待处理任务，建议去其他页面查看';
  userInfo = JSON.parse(this.ls.get('loginInfo'));
  isGq = false;
  // isGq = this.userInfo.N_LEVEL == 10;
  vcDdspNote: any;
  listOfOption: any;
  listOptionsString: string;
  queryData: any = {};
  summaryVisible = false;
  sumaryDisable = false;
  tableLoading = false;
  saveable: boolean;
  freshTree = true;
  deleteIds: any;
  lastDeleteRow: any;

  btnsControl = {
    view: false,
    cjbz: false,
    ddsp: false,
    gqqs: false,
    gqbz: false,
    dypgd: false,
    pgdxj: false,
    cjsh: false,
    ddsh: false,
  };
  peopleList: any;
  allPeopleList: any;
  vcDdshXjnote: string;
  bgryArr: any = []; // 选中项
  bgryList: any = []; // 所有可选项
  bgryList_filter: any = [];
  lastSanfangIndex: any;
  messageIndex = 0;
  messageIndexArr = [];
  constructor(
    private apiService: ApiService,
    public msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    public ls: LocalStorage,
    private reuseTabService: ReuseTabService,
    private exportFile: ExportFileService,
    private http: _HttpClient,
    private modalService: NzModalService,
    public treeTools: TreeTools,
    private statusFollowService: StatusFollowService,
    private messageListenerTools: MessageListenerTools,
    private datePipe: DatePipe
  ) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      if (params.status == 'shop') {
        this.reuseTabService.title = '派工单编制';
        this.pagetype = 'cjbz';
        // this.showSubmit = true;
        this.editable = true;
      }
      if (params.status == 'ddsp') {
        this.reuseTabService.title = '派工单审批';
        this.pagetype = 'ddsp';
        // this.showSubmit = true;
        this.editable = false;
      }
      if (params.status == 'work') {// 主页面去掉提交,增加签收7,且不能修改,弹窗去掉修改按钮
        this.reuseTabService.title = '工区天窗计划签收';
        this.pagetype = 'gqqs';
        // this.showSubmit = false;
        this.editable = false;
      }
      if (params.status == 'edit') {//
        this.reuseTabService.title = '工区派工单编制';
        this.pagetype = 'gqbz';
        // this.showSubmit = true;
        this.editable = true;
      }
      if (params.status == 'dypgd') {//
        this.reuseTabService.title = '派工单导出';
        this.pagetype = 'dypgd';
        // this.showSubmit = true;
        this.editable = false;
      }
      if (params.status == 'view') {//
        this.reuseTabService.title = '派工单';
        this.pagetype = 'view';
        // this.showSubmit = true;
        this.editable = false;
      }
      if (params.status == 'pgdxj') {//
        this.reuseTabService.title = '工区作业小结';
        this.pagetype = 'pgdxj';
        this.editable = false;
      }
      if (params.status == 'cjsh') {//
        this.reuseTabService.title = '车间作业小结';
        this.pagetype = 'cjsh';
        this.editable = false;
      }
      if (params.status == 'ddsh') {//
        this.reuseTabService.title = '调度审核完成小结';
        this.pagetype = 'ddsh';
        this.editable = false;
      }
      this.readyload(this.rowPage, this.pageValue);
    });
    // temp data
    this.examData = [{ 'id': '1' }, { 'id': '2' }];
    this.initState();
    this.getCj();
    this.initMenus();
    this.getAllPeople();
    if (this.userInfo.N_LEVEL == 30) {
      this.initCjPeople();
    }
    const listener = (event) => { 
      if (event.origin !== window.location.protocol + '//' + window.location.host) {
        return;
      }
      const data = event.data;
      if (data.text) {
        data.text = data.text.replace(/<br>/g, '');
      }
      if (data.tips) {
        data.tips = data.tips.replace(/<br>/g, '');
      }
      if (this.messageIndexArr.length || this.lastSanfangIndex !== 'undefined') {
        switch (data.type) {
          case '1': // 人员类型
            this.addData[this.lastSanfangIndex].vcRiskControl += ` （${data.text}）`;
            break;
          case '2': // 三防
            this.messageIndexArr[this.lastSanfangIndex]++;
            if (this.addData[this.lastSanfangIndex].vcRiskControl) {
              this.addData[this.lastSanfangIndex].vcRiskControl += '\n' + `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.text;
            } else {
              this.addData[this.lastSanfangIndex].vcRiskControl = `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.text;
            }
            if (this.addData[this.lastSanfangIndex].vcDingkongRequire) {
              this.addData[this.lastSanfangIndex].vcDingkongRequire += '\n' + `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.tips;
            } else {
              this.addData[this.lastSanfangIndex].vcDingkongRequire = `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.tips;
            }
            break;
          default:
            if (this.lastSanfangIndex) {
              this.messageIndexArr[this.lastSanfangIndex]++;
              if (this.addData[this.lastSanfangIndex].vcRiskControl) {
                this.addData[this.lastSanfangIndex].vcRiskControl += '\n' + `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.text;
              } else {
                this.addData[this.lastSanfangIndex].vcRiskControl = `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.text;
              }
              if (this.addData[this.lastSanfangIndex].vcDingkongRequire) {
                this.addData[this.lastSanfangIndex].vcDingkongRequire += '\n' + `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.tips;
              } else {
                this.addData[this.lastSanfangIndex].vcDingkongRequire = `${this.messageIndexArr[this.lastSanfangIndex]}.` + data.tips;
              }
            }
            break;
        }
      }
    };
    this.messageListenerTools.init(listener);
  }

  _onReuseInit() {
    this.readyload(this.rowPage, this.pageValue);
  }

  statusFollow(data) {
    return this.statusFollowService.init('1', data);
  }

  initMenus() {
    const level = this.userInfo.N_LEVEL;
    if (level == 10) {
      this.btnsControl.view = true;
      this.btnsControl.gqqs = true;
      this.btnsControl.gqbz = true;
      this.btnsControl.dypgd = true;
      this.btnsControl.pgdxj = true;
    } else if (level == 30) {
      this.btnsControl.view = true;
      this.btnsControl.cjbz = true;
      this.btnsControl.dypgd = true;
      this.btnsControl.cjsh = true;
    } else if (level == 50) {
      this.btnsControl.view = true;
      this.btnsControl.ddsp = true;
      this.btnsControl.dypgd = true;
      this.btnsControl.ddsh = true;

    }
  }

  initState() {
    this.listOfOption = [
      { value: '-1', label: '全选' },
      { value: '0', label: '计划已导入' },
      { value: '1', label: '领导审批中' },
      { value: '2', label: '领导已批准' },
      { value: '3', label: '领导已驳回' },
      { value: '4', label: '车间已签收' },
      { value: '5', label: '车间编制中' },
      { value: '6', label: '车间已下发' },
      { value: '7', label: '工区已签收' },
      { value: '8', label: '工区已提报' },
      { value: '9', label: '车间已审核' },
      { value: '10', label: '车间已驳回' },
      { value: '11', label: '调度已批准' },
      { value: '12', label: '调度已驳回' },
      { value: '13', label: '小结已填写' }
    ];
    for (const item of this.listOfOption) {
      this.listOfTagOptions.push(item.value);
    }
  }

  getColorByStatus(status, _color) {
    if (!status) {
      return;
    }

    if (['0', '5'].includes(status)) {// 编制
      return 'grey' == _color;
    } else if (['3', '10', '12', '15', '17'].includes(status)) {
      return 'red' == _color;
    } else {
      return 'green' == _color;
    }
  }

  getColorClass(status) {
    return {
      red: this.getColorByStatus(status, 'red'),
      green: this.getColorByStatus(status, 'green'),
      '': this.getColorByStatus(status, 'grey'),
    };
  }

  // 状态
  listOfTagChange(list) {
    setTimeout(() => {
      for (const item of list) {
        if (item == '-1') {
          this.listOfTagOptions = [];
          this.listOptionsString = '';
          for (const data of this.listOfOption) {
            this.listOfTagOptions.push(data.value);
          }
          break;
        } else {
          this.listOptionsString = this.listOfTagOptions.join(',');
        }
      }
    }, 500);
  }

  getIbyIndex(index) {
    let count = 0;
    for (let i = 0; i <= index; i++) {
      const row = this.examData[i];
      if (row.rowspans && -row.rowspans < 0) {
        count += 1;
      }
    }
    return count;
  }

  getStationByOrgId(orgId, sendindex) {
    this.tabCmpData[sendindex].staselectedList = [];
    this.apiService.getStationByOrgId(orgId, '1').subscribe((res: any) => {
      if (res.length) {
        this.tabCmpData[sendindex].staselectedList = this.treeTools.formatSelectNode(res);
      } else {
        this.tabCmpData[sendindex].staselectedList.push({});
      }
    });
  }

  getDevTypesByStaId(staId, sendindex) {
    this.tabCmpData[sendindex].workdevTypeselectedList = [];
    this.addData[sendindex].workdevType = '';
    this.apiService.getAllTypesByStaId(staId).subscribe((res: any) => {
      if (res && !res.length) {
        res = [{}];
      }
      this.zorronigebiaozi = false;
      setTimeout(() => {
        // this.tabCmpData[sendindex].workdevTypeselectedList = res;
        this.tabCmpData[sendindex].workdevTypeselectedList = this.treeTools.formatTreeNode(res);
        this.zorronigebiaozi = true;
      }, 10);
    });
  }

  getdevTypelevelBydevTypeId(devTypeId, sendindex) {
    this.tabCmpData[sendindex].workdevLevelselectedList = [];
    this.apiService.getdevTypelevelBydevTypeId(devTypeId).subscribe((res: any) => {

      if (res.length) {
        this.tabCmpData[sendindex].workdevLevelselectedList = res;
        this.tabCmpData[sendindex].workdevLevelselectedList.unshift({
          levelName: '请选择',
          levelCode: ''
        });

        if (!this.addData[sendindex].vcEquClass) {
          this.addData[sendindex].vcEquClass = res[1].levelCode;
          this.workdevLevelselectedChange(res[1].levelCode, sendindex);
        }
        // if (!this.addData[sendindex].vcEquClass) {
        // }
      } else {
        this.tabCmpData[sendindex].workdevLevelselectedList = [{}];
      }
    });
  }

  workorgselectedChange(e, sendindex) {
    this.addData[sendindex].vcSta = '';
    this.getStationByOrgId(e, sendindex);

    this.addData[sendindex].vcEquType = '';
    this.tabCmpData[sendindex].workdevTypeselectedList = [];

    this.addData[sendindex].vcEquClass = '';
    this.tabCmpData[sendindex].workdevLevelselectedList = [];

    this.tabCmpData[sendindex].workdevListForsel = [];

    // this.getPeople(res => {
    //     this.tabCmpData[sendindex].peopleList = res;
    //     this.resetPeople(sendindex);
    // }, e);

  }

  workstaselectedChange(e, sendindex) {
    this.addData[sendindex].vcEquType = '';
    this.getDevTypesByStaId(e, sendindex);

    this.addData[sendindex].vcEquClass = '';
    this.tabCmpData[sendindex].workdevLevelselectedList = [];

    this.tabCmpData[sendindex].workdevListForsel = [];
    // setTimeout(() => {
    // }, 500);
  }

  workdevTypeselectedChange(e, sendindex) {
    this.addData[sendindex].vcEquClass = '';
    this.getdevTypelevelBydevTypeId(e, sendindex);

    this.tabCmpData[sendindex].workdevListForsel = [];
  }


  workdevLevelselectedChange(e, sendindex) {
    this.tabCmpData[sendindex].workdevListForsel = [];
    this.getEquipmentData(e, sendindex);
  }

  getEquipmentData(e, sendindex, func?) {
    this.apiService.equipmentData(
      this.addData[sendindex].vcSta,
      this.addData[sendindex].vcEquType, '', e).subscribe((res: any) => {
        if (res.type === 'success') {
          this.tabCmpData[sendindex].workdevListForsel = res.data.pageList;
          this.tabCmpData[sendindex].workdevListForsel_xj = JSON.parse(JSON.stringify(res.data.pageList));
          if (func) {
            func();
          }
        }
      });
  }

  formatPeopleData(data: any) {
    if (data.length) {
      data.forEach((node: any) => {
        node.key = node.id;
        node.title = node.text;
        if (node.children && node.children.length) {
          this.formatPeopleData(node.children);
        } else {
          // delete node.children;
          node.isLeaf = true;
        }
      });
    }
  }

  getPeople(func, id) {
    if (this.isGq) {
      if (this.peopleList && this.peopleList.length) {
        if (func) {
          func();
        }
        return;
      }
      const url = environment.apiBase + '/csmis/person/getOrgPersonListById.jwt?isWorklist=1&orgId=' + id;
      this.http.get(url).subscribe((res: any) => {
        this.peopleList = res;
        if (func) {
          func();
        }
      });
    } else {
      const url = environment.apiBase + '/csmis/csmisEquadjust/wswatree.jwt?isWorklist=1&orgid=' + id;
      this.http.get(url).subscribe((res: any) => {
        this.formatPeopleData(res);
        // this.peopleList = res;
        func(res);
      });
    }
  }

  // 获取用户所属车间人员
  initCjPeople() {
    this.apiService.chargesData(this.userInfo.VC_ORG$ID).subscribe(res => { 
      this.bgryList = res;
      this.bgryList_filter = res;
    });
  }

  // setBgry(v) {
  //   if (this.bgry) {
  //     if (this.bgry.includes(v)) {
  //       return;
  //     } else {
  //       this.bgry += "、" + v;
  //     }
  //   } else {
  //     this.bgry = v;
  //   }
  // }

  getAllPeople(func?) {
    const url = environment.apiBase + '/csmis/csmisEquadjust/wswatree.jwt?isWorklist=1';
    this.http.get(url).subscribe((res: any) => {
      this.formatPeopleData(res);
      this.allPeopleList = res;
      if (func) {
        func(res);
      }
    });
  }

  readyload(page, rows) {
    this.pageIndex = page;
    this.checkIndexes.clear();
    this.tableLoading = true;
    this.apiService.finddayworksgrwxPGD(
      page, rows,
      this.datePipe.transform(this.zyrqValue1, 'yyyy-MM-dd'),
      this.datePipe.transform(this.zyrqValue2, 'yyyy-MM-dd'),
      this.pagetype == 'view' ? '' : this.pagetype,
      this.listOptionsString || '',
      this.queryParam.cj || '',
      this.queryParam.gq || '',
      '',
      this.queryParam.cz || '',
    ).subscribe((res: any) => {
      this.tableLoading = false;
      if (res.type === 'success') {
        this.examData = res.data.pageList;
        this.examData.forEach(row => {
          if (row.VC_OUT$SAFER) {
            const arr = row.VC_OUT$SAFER.split(',');
            let up = '';
            let down = '';
            if (arr[0]) {
              up = arr[0].replace(/\-/g, '、');
            }
            if (arr[1]) {
              down = arr[1].replace(/\-/g, '、');
            }
            row._VC_OUT$SAFER = `上行：${up || ''} <br>下行：${down || ''}`;
          }
        });
        this.pageTotal = res.data.pageCount;
        this.rowTotal = res.data.pageCount;
        this.rebuilddata();
      }
    });
  }

  rebuilddata() {
    let rwxgh = '';
    let rowspans = '1';
    let startrow = '';
    for (let i = 0; i < this.examData.length; i++) {
      const el = this.examData[i];
      el.disabled = true;
      if (el.RWXID == rwxgh) {
        el.rowspans = 0;
        this.examData[startrow].rowspans = this.examData[startrow].rowspans + 1;
      } else {
        rwxgh = el.RWXID;
        rowspans = '1';
        startrow = i + '';
        el.rowspans = 1;
        this.examData[startrow].disabled = false;
      }
    }
  }


  getPeopleName(id) {
    if (!id) {
      return;
    }
    if (!this.allPeopleList || !this.allPeopleList.length) {
      return;
    }
    const node = this.getNodeFromTreeNodes(id, this.allPeopleList);
    if (node) {
      return node.title;
    }
  }

  getNodeFromTreeNodes(id, nodes) {
    let _node;
    nodes.forEach(node => {
      if (node.children && node.children.length) {
        const res = this.getNodeFromTreeNodes(id, node.children);
        if (res) {
          _node = res;
        }
      } else if (node.key == id) {
        _node = node;
      }
    });
    return _node;
  }

  dataviewDbclick2(data) {
    this.messageIndexArr = [];
    if (['pgdxj', 'cjsh', 'ddsh'].includes(this.pagetype)) {
      this.summaryVisible = true;
    } else if (this.pagetype == 'view') {
      if (data.RWXVCSTATUS == '13') {
        this.summaryVisible = true;
        this.sumaryDisable = !this.editable;
      } else {
        this.dataviewVisible = true;
      }
      this.freshTree = false;
    } else if (this.pagetype == 'dypgd') {
      this.dataviewVisible = true;
      this.freshTree = false;
    } else {
      this.dataviewVisible = true;
    }
    this.addData = [];
    this.deleteIds = [];
    this.dataviewTabs = ['维修日计划信息']; // add by zz
    this.mainRow = data;
    this.tabCmpData = [];
    this.getZyxm(data.RWXTYPE);
    this.saveable = false;
    let orgid;
    if (this.userInfo.N_LEVEL == 50) {
      orgid = data.VC_ORG$ID;
    }
    this.apiService.getgongquByCjId(orgid || '').subscribe((res: any) => {
      if (res && !res.length) {
        res = [{}];
      }

      const RWXID = data.RWXID;
      const rows = this.examData.filter(row => row.RWXID == RWXID);
      rows.sort((row1, row2) => {
        return row1.N_ID - row2.N_ID;
      })
      let trans;
      if (['pgdxj', 'cjsh', 'ddsh'].includes(this.pagetype) || this.mainRow.RWXVCSTATUS == '13') {
        trans = { ...this.fieldTrans_low2up_xj, ...this.fieldTrans_low2up };
      } else {
        trans = this.fieldTrans_low2up;
      }
      this.swfwy_isNormal = new Array(rows.length);
      this.swfwy_isNormal.fill(false);
      rows.forEach((row, index) => {
        this.dataviewTabs.push('派工单—' + (row.VC_GROUP || ''));
        this.tabsVisiable[index + 1] = false;
        const saveRow: any = {};
        Object.entries(trans).forEach((el: any) => {
          const low = el[0], up = el[1];
          if (low && up) {
            if (row[up] == 0) {
              saveRow[low] = '0';
            } else {
              saveRow[low] = row[up] || '';
            }
            // saveRow[low] = row[up] || "";
          }
        });
        if (saveRow.vcGroup) {
          saveRow.vcGroupName = this.getPeopleName(saveRow.vcGroup);
        }
        if (saveRow.vcInSafer) {
          saveRow.vcInSaferName = this.getPeopleName(saveRow.vcInSafer);
        }
        if (saveRow.vcOutSafer) {
          if (saveRow.vcOutSafer.includes(',')) {
            // this.swfwy_isNormal[index] = false;
            const ids = saveRow.vcOutSafer.split(',');
            saveRow._vcOutSafer1 = ids[0].split('-');
            saveRow._vcOutSafer2 = ids[1].split('-');
          } else {
            // this.swfwy_isNormal[index] = true;
            saveRow._vcOutSafer = saveRow.vcOutSafer.split('-');
          }
          // else {
          //     saveRow.vcOutSaferName = this.getPeopleName(saveRow.vcOutSafer);
          // }
        }
        if (saveRow.vcTeammen) {
          saveRow._vcTeammen = saveRow.vcTeammen.split(',');
          const names = [];
          saveRow._vcTeammen.forEach(id => {
            names.push(this.getPeopleName(id));
          });
          saveRow.vcTeammenNames = names.join('、');
        }
        if (saveRow.vcWorkStime) {
          const times = saveRow.vcWorkStime.split(':');
          const _date = new Date();
          _date.setHours(times[0]);
          _date.setMinutes(times[1]);
          saveRow._vcWorkStime = _date;
        } else {
          saveRow._vcWorkStime = new Date();
        }
        if (saveRow.vcWorkEtime) {
          const times = saveRow.vcWorkEtime.split(':');
          const _date = new Date();
          _date.setHours(times[0]);
          _date.setMinutes(times[1]);
          saveRow._vcWorkEtime = _date;
        } else {
          saveRow._vcWorkEtime = new Date();
        }
        if (saveRow.vcProject) {
          this.zyxmClick(saveRow.vcProject, index);
        }
        if (!saveRow.vcTool) {
          saveRow.vcTool = "工器具已准备到位";
        }
        if (!saveRow.vcKtrequire) {
          saveRow.vcKtrequire = `1.工器具检查完毕\n2.实验良好\n3.箱盒设备锁闭良好\n4.正点销记交付`;
        }
        // if (saveRow.vcFinishedornot == '1') {
        //     saveRow._vcFinishedornot = true;
        // } else {
        //     saveRow._vcFinishedornot = false;
        // }
        saveRow._adddevnames = '';
        saveRow.adddevnames = '';
        this.addData.push(saveRow);
        const cmpData = {
          orgselectedList: res,
          staselectedList: [],
          workdevTypeselectedList: [],
          workdevLevelselectedList: [],
          workdevListForsel: [],
          peopleList: []
        };
        this.tabCmpData.push(cmpData);
      });

      this.addData.RWXID = RWXID;
    });
  }

  /**
   *
   * @param gqId
   * @param czId
   * @param sblxId
   * @param sbfjId
   * @param index  标签页面号减1
   */
  getCmpData(gqId, czId, sblxId, sbfjId, index) {
    if (!this.tabCmpData[index].staselectedList.length) {
      if (gqId) {
        this.getStationByOrgId(gqId, index);
      }
    }
    if (!this.tabCmpData[index].workdevTypeselectedList.length) {
      if (czId) {
        this.getDevTypesByStaId(czId, index);
      }
    }
    if (!this.tabCmpData[index].workdevLevelselectedList.length) {
      if (sblxId) {
        this.getdevTypelevelBydevTypeId(sblxId, index);
      }
    }
    if (!this.tabCmpData[index].workdevListForsel.length) {
      if (sbfjId) {
        // this.workdevLevelselectedChange(sbfjId, index);
        this.getEquipmentData(sbfjId, index, () => {
          this.setCheckBoxesValue(this.addData[index].vcDevId, this.tabCmpData[index].workdevListForsel);
          if (['pgdxj', 'cjsh', 'ddsh'].includes(this.pagetype) || this.mainRow.RWXVCSTATUS == '13') {
            this.setCheckBoxesValue(this.addData[index].vcFinished, this.tabCmpData[index].workdevListForsel_xj);
          }
        });
        // this.workdevLevelselectedChange(sbfjId, index);
      }
    }
    if (!this.tabCmpData[index].peopleList.length) {
      if (this.freshTree) {
        this.getPeople(res => {
          this.tabCmpData[index].peopleList = res;
          this.resetPeople(index);
        }, this.userInfo.VC_ORG$ID);
      }
      // if (gqId) {
      // }
    }
    if (this.freshTree == false) {
      if (!this.allPeopleList || this.allPeopleList.length) {
        this.getAllPeople(res => {
          this.allPeopleList = res;
        });
      }
    }
  }

  resetPeople(index) {
    this.freshTree = false;
    setTimeout(() => {
      this.freshTree = true;
    }, 100);
  }

  getValueFromCheckBoxes(checkboxNodes: any) {
    if (!checkboxNodes) {
      return [];
    }
    const ids = [], names = [];
    checkboxNodes.forEach((checkboxNode: any) => {
      if (checkboxNode.checked) {
        ids.push(checkboxNode.opValue || '');
        names.push(checkboxNode.opName || '');
      }
    });
    return [ids, names];
  }

  /**
   *
   * @param vcDevId
   * @param checkboxesData this.tabCmpData[index].workdevListForsel
   */
  setCheckBoxesValue(vcDevId, checkboxesData) {
    const vcDevIdArr = vcDevId.split(',');
    vcDevIdArr.forEach(id => {
      checkboxesData.forEach(el => {
        if (el.opValue == id) {
          el.checked = true;
        }
      });
    }); 

  }

  // setCheckBoxesValue(vcDevId, index) {
  //     let vcDevIdArr = vcDevId.split(',');
  //     vcDevIdArr.forEach(id => {
  //         this.tabCmpData[index].workdevListForsel.forEach(el => {
  //             if (el.opValue == id) {
  //                 el.checked = true;
  //             }
  //         });
  //     }); 

  // }

  getOptionNodeName(id, nodes) {
    for (const item of nodes) {
      if (item.opValue == id) {
        return item.opName;
      }
    }
  }

  beforeSave() {
    this.addData.forEach((data, index) => {
      const devs = this.getValueFromCheckBoxes(this.tabCmpData[index].workdevListForsel);
      if (devs.length) {
        const vcDevId = devs[0];
        const vcDevName = devs[1];
        // 前半部分表示checkbox加载过，此时不管vcDevId和vcDevName有没有值都可认为用户已经做过设置
        // 后半部分表示checkbox有值，可认为用户已经做出选择
        // 其他情况表示checkbox没有加载（因为用户没有激活过TAB），此时设备的值为原值
        if (this.tabCmpData[index].workdevListForsel.length || (vcDevId.length && vcDevName.length)) {
          data.vcDevId = vcDevId.join();
          data.vcDevName = vcDevName.join();
        }
      }
      if (data._vcTeammen && data._vcTeammen.length) {
        data.vcTeammen = data._vcTeammen.join();
      }
      if (data._adddevnames) {
        data.adddevnames = data._adddevnames.replace(/，/g, ',');
      }
    });
  }

  dataviewOk() {
    this.beforeSave();
    this.saveAllTab(this.addData);

  }

  dataviewCancel() {
    this.dataviewVisible = false;
  }

  closeTab(tab) {
    const count = JSON.parse(JSON.stringify(this.dataviewTabs)).length;
    const index = this.dataviewTabs.indexOf(tab);

    if (index && count > 2) {
      this.dataviewTabs.splice(index, 1);
      this.tabActiveIndex -= 1;
      if (this.tabActiveIndex < 0) {
        this.tabActiveIndex = 0;
      }
      const deleteRow = this.addData.splice(index - 1, 1);
      this.tabCmpData.splice(index - 1, 1);
      this.lastDeleteRow = JSON.parse(JSON.stringify(deleteRow[0]));
      if (deleteRow.length && deleteRow[0].nnId) {
        this.deleteIds.push(deleteRow[0].nnId);
      }
    }
  }

  newTab() {
    this.dataviewTabs.push('派工单');
    let lastRow;
    if (this.addData.length && this.addData.length > 0) {
      if (this.tabActiveIndex == 0) {
        lastRow = this.addData[0];
      } else {
        lastRow = this.addData[this.tabActiveIndex - 1];
      }
    } else {
      lastRow = this.lastDeleteRow;
    }
    const copy = JSON.parse(JSON.stringify(lastRow));
    const field_del = [
      'nnId',
      'vcProject',
      // 'vcOrgId',
      // 'vcSta',
      'vcEquType',
      'vcEquClass',
      'vcDevId',
      'vcDevName',
      'vcGroup',
      'vcInSafer',
      'vcOutSafer',
      'vcTeammen',
      '_vcTeammen',
      'RWXPROJECT',
      'vcWorkorder',
      'vcTool',
      'vcInouttype',
      'vcKtrequire',
      'vcRiskControl',
      'vcDingkongRequire',
    ];
    field_del.forEach(field => {
      copy[field] = '';
    });
    this.removePrivateField(copy);
    if (!copy.vcTool) {
      copy.vcTool = "工器具已准备到位";
    }
    if (!copy.vcKtrequire) {
      copy.vcKtrequire = `1.工器具检查完毕\n2.实验良好\n3.箱盒设备锁闭良好\n4.正点销记交付`;
    }
    this.addData.push(copy);

    let lastTabCmpData = this.tabCmpData[this.tabCmpData.length - 1];
    if (this.tabActiveIndex != 0) {
      lastTabCmpData = this.tabCmpData[this.tabActiveIndex - 1];
    }
    const orgselectedList = JSON.parse(JSON.stringify(lastTabCmpData.orgselectedList));
    const cmpData = {
      orgselectedList,
      staselectedList: [],
      workdevTypeselectedList: [],
      workdevLevelselectedList: [],
      workdevListForsel: [],
      peopleList: []
    };

    this.tabCmpData.push(cmpData);
    setTimeout(() => {
      this.tabActiveIndex = this.dataviewTabs.length - 1;
    }, 100);
  }

  newTab_allCopy() {
    this.dataviewTabs.push('派工单');
    let lastRow;
    if (this.addData.length && this.addData.length > 0) {
      if (this.tabActiveIndex == 0) {
        lastRow = this.addData[0];
      } else {
        lastRow = this.addData[this.tabActiveIndex - 1];
      }
    } else {
      lastRow = this.lastDeleteRow;
    }
    const copy = JSON.parse(JSON.stringify(lastRow));
    const field_del = [
      'nnId',
      '_vcTeammen',
    ];
    field_del.forEach(field => {
      copy[field] = '';
    });
    if (!copy.vcTool) {
      copy.vcTool = "工器具已准备到位";
    }
    if (!copy.vcKtrequire) {
      copy.vcKtrequire = `1.工器具检查完毕\n2.实验良好\n3.箱盒设备锁闭良好\n4.正点销记交付`;
    }
    this.addData.push(copy);

    let lastTabCmpData = this.tabCmpData[this.tabCmpData.length - 1];
    if (this.tabActiveIndex != 0) {
      lastTabCmpData = this.tabCmpData[this.tabActiveIndex - 1];
    }
    this.tabCmpData.push(lastTabCmpData);
    setTimeout(() => {
      this.tabActiveIndex = this.dataviewTabs.length - 1;
    }, 100);
  }


  yearselectedChange() {
    this.pageValue = this.selectedValue;
    this.readyload(this.rowPage, this.pageValue);
  }

  rowChangeTable1(ev) {
    this.rowPage = ev;
    this.readyload(this.rowPage, this.pageValue);
  }

  currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
    this.displayData = $event;
    this.refreshStatus();
  }

  refreshStatus(e?, i?): void {
    const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked == true);
    const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);

    // let index = this.getIbyIndex(i);
    if (e == true) {
      this.checkIndexes.add(i);
    } else if (e == false) {
      this.checkIndexes.delete(i);
    }

  }

  checkAll(value: boolean): void {
    this.checkIndexes.clear();
    this.displayData.forEach((data, i) => {
      if (!data.disabled) {
        data.checked = value;
        // let index = this.getIbyIndex(i);
        if (value == true) {
          this.checkIndexes.add(i);
        } else if (value == false) {
          this.checkIndexes.delete(i);
        }
      }
    });
    this.refreshStatus();
  }

  judgeParam(param) {
    let saveable = true;
    if (!param.vcProject) {
      this.msg.warning('请选择作业项目');
      saveable = false;
    }
    if (!param.vcSta) {
      this.msg.warning('请选择车站');
      saveable = false;
    }
    if (!param.vcOrgId) {
      this.msg.warning('请选择工区');
      saveable = false;
    }
    if (!param.vcEquType) {
      this.msg.warning('请选择设备类型');
      saveable = false;
    }
    return saveable;
  }

  getOneTabOb(param, index) {
    if (!param) {
      return;
    }
    param.vcSource = '5';
    if (this.swfwy_isNormal[index] == false) {
      if (param._vcOutSafer1 || param._vcOutSafer2) {
        if (param._vcOutSafer1 && param._vcOutSafer2) {
          param.vcOutSafer = param._vcOutSafer1.join('-') + ',' + param._vcOutSafer2.join('-');
        } else {
          this.msg.warning(`请将 第${index + 1}号派工单 室外防护员 上下行填写完整`);
          return false;
        }
      }
    } else {
      if (param._vcOutSafer && param._vcOutSafer.length) {
        param.vcOutSafer = param._vcOutSafer.join('-');
      }
    } 
    if (this.judgeParam(param) == false) {
      return false;
    }
    this.removePrivateField(param); 
    // return false;
    const url = environment.apiBase + '/csmis/prod/updateymwaday.jwt';
    return this.http.post(url, param, { adddevnames: param.adddevnames }, { headers: responseHeaders });
  }

  /**
   * 补0
   */
  completeTime(timeNum) {
    if (timeNum < 10) {
      timeNum = '0' + timeNum;
    }
    return timeNum;
  }

  removePrivateField(param) {
    Object.keys(param).forEach(key => {
      if (key.indexOf('_') == 0) {
        delete param[key];
      }
    });
  }

  getOneTabSummaryOb(_param, index) {
    if (!_param) {
      return;
    }
    const param: any = {};
    // param.vcSource = '5';
    if (_param._vcWorkStime) {
      const hour = _param._vcWorkStime.getHours();
      const minute = _param._vcWorkStime.getMinutes();
      param.vcWorkStime = this.completeTime(hour) + ':' + this.completeTime(minute);
    }
    if (_param._vcWorkEtime) {
      const hour = _param._vcWorkEtime.getHours();
      const minute = _param._vcWorkEtime.getMinutes();
      param.vcWorkEtime = this.completeTime(hour) + ':' + this.completeTime(minute);
    }
    // 开始时间与结束时间相等视为没填
    if (param.vcWorkStime == param.vcWorkEtime) {
      param.vcWorkStime = '';
      param.vcWorkEtime = '';
    }
    // if (_param._vcFinishedornot == true) {
    //     param.vcFinishedornot = '1';
    // } else {
    //     param.vcFinishedornot = '0';
    // }

    const devs_xj = this.getValueFromCheckBoxes(this.tabCmpData[index].workdevListForsel_xj);
    if (devs_xj.length) {
      const vcDevId = devs_xj[0];
      param.vcFinished = vcDevId.join();
    }
    if (this.swfwy_isNormal[index] == false) {
      if (_param._vcOutSafer1 || _param._vcOutSafer2) {
        if (_param._vcOutSafer1 && _param._vcOutSafer2) {
          param.vcOutSafer = _param._vcOutSafer1.join('-') + ',' + _param._vcOutSafer2.join('-');
        } else {
          this.msg.warning(`请将 第${index + 1}号派工单 室外防护员 上下行填写完整`);
          return false;
        }
      }
    } else {
      if (param._vcOutSafer && param._vcOutSafer.length) {
        param.vcOutSafer = param._vcOutSafer.join('-');
      }
    }
    param.vcFinishedornot = _param.vcFinishedornot;
    param.vcUnfiReason = _param.vcUnfiReason;
    param.ids = _param.nnId;
    // param.vcStatus = '13';
    this.removePrivateField(param); 
    // return;
    const url = environment.apiBase + '/csmis/prod/updatewadaywork.jwt';
    return this.http.get(url, param);
  }

  /**
   * 删除派工单
   */
  deletePgd(ids) {
    const url = environment.apiBase + '/csmis/prod/deletewadaywork.jwt?ids=' + ids;
    return this.http.get(url);
  }

  asyncLoopRequest(obs, i = 0, func, panalVisiable) {
    if (obs.length && i < obs.length) {
      obs[i].subscribe(res => {
        if (res) {
          if (i == obs.length - 1) {
            this.msg.success('保存成功');
            this.readyload(this.rowPage, this.pageValue);
            if (func) {
              func();
            }
            this[panalVisiable] = false;
            return;
          }
          i++;
          this.asyncLoopRequest(obs, i, func, panalVisiable);


        }
      });
    }
  }

  saveAllTab(data, func?) {
    const obs = [];
    let panalVisiable;

    for (let i = 0; i < data.length; i++) {
      const row = data[i];
      if (!row.vcOrgId) {
        this.msg.warning('请选择工区');
        return;
      }
    }
    if (['pgdxj', 'cjsh', 'ddsh'].includes(this.pagetype)) {
      data.forEach((row, index) => {
        const ob = this.getOneTabSummaryOb(row, index);
        obs.push(ob);
      });
      panalVisiable = 'summaryVisible';
      if (obs.includes(false)) {
        return;
      }
      this.forkJoinSaves(obs, func, panalVisiable);

    } else {
      data.forEach((row, index) => {
        const ob = this.getOneTabOb(row, index);
        obs.push(ob);
      });
      panalVisiable = 'dataviewVisible';
      if (obs.includes(false)) {
        return;
      }
      // this.forkJoinSaves(obs, func, panalVisiable);
      // this.asyncLoopRequest(obs, 0, func, panalVisiable)
      if (this.deleteIds.length) {
        const ids = this.deleteIds.join();
        this.deletePgd(ids).subscribe((res: any) => {
          if (res.type === 'success') {
            this.forkJoinSaves(obs, func, panalVisiable);
            // this.asyncLoopRequest(obs, 0, func, panalVisiable)
          } else {
            this.msg.error('删除失败');
          }
        });
      } else {
        this.forkJoinSaves(obs, func, panalVisiable);
      }
    }
  }


  forkJoinSaves(obs, func, panalVisiable) {
    forkJoin(...obs).subscribe((resArr: any[]) => {
      let allResSuccess = true;
      resArr.forEach((res, index) => {
        if (!res) {
          allResSuccess = false;
        } else if (typeof res == 'object' && res.type && res.type != 'success') {
          allResSuccess = false;
        }
        if (allResSuccess == false) {
          this.msg.error(`${this.dataviewTabs[index + 1]}保存失败`);
        }
      });
      if (allResSuccess) {
        this.msg.success('保存成功');
        this.readyload(this.rowPage, this.pageValue);
        if (func) {
          func();
        }
        this[panalVisiable] = false;
        // this.dataviewVisible = false;
      }
    });
  }

  onTabIndexChange(index) {
    if (index == 0) {
      return;
    }
    this.tabsVisiable[index] = true;
    this.tabActiveIndex = index;
    const i = index - 1;
    if (this.addData[i]) {
      const gqId = this.addData[i].vcOrgId;
      const czId = this.addData[i].vcSta;
      const sblxId = this.addData[i].vcEquType;
      const sbfjId = this.addData[i].vcEquClass;
      this.getCmpData(gqId, czId, sblxId, sbfjId, i);
    }
  }

  /**
   * 主表勾选提交
   */
  dataviewSubmit(content?) {
    const RWXIDs = [];
    this.checkIndexes.forEach((v: any) => {
      RWXIDs.push(this.examData[v].RWXID);
    });
    const ids = RWXIDs.join();
    if (!ids.length) {
      this.msg.error('请先选择一条数据');
      return;
    }
    let vcStatus;
    let optName = '';
    let doConfirm = true;
    switch (this.pagetype) {
      case 'cjbz':
        vcStatus = '9';
        optName = '提报';
        break;
      case 'gqqs':
        vcStatus = '7';
        optName = '签收';
        break;
      case 'gqbz':
        vcStatus = '8';
        optName = '提报';
        break;
      case 'pgdxj':
        vcStatus = '13';
        optName = '保存';
        doConfirm = false;
        break;
      case 'cjsh':
        vcStatus = '13';
        optName = '保存';
        doConfirm = false;
        break;
    }
    if (doConfirm == true) {
      this.bgryArr = [];
      this.modalService.confirm({
        nzTitle: `<i>确认</i>`,
        nzWidth: '600',
        nzContent: content ? content : `<b>确认${optName}吗?</b>`,
        nzOnOk: () => {
          if (vcStatus) {
            this.apiService.updatesgrwxPerson(ids, '', vcStatus, '', '', '', this.bgryArr.join('、'))
              .subscribe(_res => {
                const res = JSON.parse(_res);
                if (res.type === 'success') {
                  this.msg.success(optName + '成功');
                  this.readyload(this.rowPage, this.pageValue);
                } else {
                  this.msg.error(optName + '失败');
                }
              });
          }
        }
      });
    } else {
      // const ids = this.addData.RWXID;
      if (vcStatus) {
        this.apiService.updatesgrwxPerson(ids, '', vcStatus, '', '', '')
          .subscribe(_res => {
            const res = JSON.parse(_res);
            if (res.type === 'success') {
              this.msg.success(optName + '成功');
              this.readyload(this.rowPage, this.pageValue);
            } else {
              this.msg.success(optName + '失败');
            }
          });
      }
    }
  }

  /**
   * 驳回
   */
  dataviewReject(_content) {
    let vcStatus;
    let optName = '';
    let needJudge = false;
    let content = `<b>确认${optName}吗?</b>`;
    switch (this.pagetype) {
      case 'cjbz':
        vcStatus = '10';
        optName = '驳回';
        content = '';
        needJudge = true;
        break;
      case 'cjsh':
        vcStatus = '15';
        optName = '驳回';
        content = '';
        needJudge = true;
        break;
      case 'ddsh':
        vcStatus = '17';
        optName = '驳回';
        needJudge = false;
        content = _content;
        break;
    }

    const RWXIDs = [];
    let exist = false;
    this.checkIndexes.forEach((v: any) => {
      const row = this.examData[v];
      if (row.VC_CJORGQ == '1' || needJudge == false) {
        RWXIDs.push(this.examData[v].RWXID);
      } else {
        exist = true;
      }
    });
    const ids = RWXIDs.join();
    if (!RWXIDs.length) {
      this.msg.warning(`您勾选的记录中没有可${optName}的有效条目（可能因为其并非工区提报）`);
      return;
    }
    if (exist) {
      this.msg.warning(`您勾选的记录中存在不可${optName}的条目（可能因为其并非工区提报），系统将对其他条目进行${optName}处理`);
    }
    this.modalService.confirm({
      nzTitle: `<b>确认${optName}吗?</b>`,
      nzWidth: '600',
      nzContent: content,
      nzOnOk: () => {

        // return;
        if (vcStatus) {
          this.apiService.updatesgrwxPerson(ids, '', vcStatus, '', '', '')
            .subscribe(_res => {
              const res = JSON.parse(_res);
              if (res.type === 'success') {
                // if (exist) {
                //     this.msg.success(optName + '成功,其中存在无法驳回的记录,作出自动跳过处理');
                // } else {
                //     this.msg.success(optName + '成功');
                // }
                this.msg.success(optName + '成功');
                this.readyload(this.rowPage, this.pageValue);
              } else {
                // if (exist) {
                //     this.msg.error(optName + '失败,其中存在无法驳回的记录,作出自动跳过处理');
                // } else {
                //     this.msg.error(optName + '失败');
                // }
                this.msg.error(optName + '失败');
              }
            });
        }
      }
    });

  }

  /**
   * 调度审批批准/驳回
   */
  dataviewSp(isPass, _content, _content_xj?) {
    this.vcDdspNote = '';
    this.vcDdshXjnote = '';
    let vcStatus;
    let optName = '';
    let content = _content;
    let note = this.vcDdspNote;
    if (isPass == true) {// 批准
      if (this.pagetype == 'ddsh') {
        vcStatus = '16';
        content = _content_xj;
        note = this.vcDdshXjnote;
      } else if (this.pagetype == 'ddsp') {
        vcStatus = '11';
      }
      optName = '签收';
    } else if (isPass == false) {// 驳回
      vcStatus = '12';
      optName = '驳回';
    }
    // <td>{{item.VC_DDSP$PERSON}}</td> vcDdspPerson
    //                         <td>{{item.VC_DDSP$NOTE}}</td> vcDdspNote
    //                         <td>{{item.DT_DDSPDATE}}</td> dtDdspdate
    this.modalService.confirm({
      nzTitle: `<b>确认${optName}吗?</b>`,
      nzWidth: '600',
      nzContent: content,
      // nzContent: `<b>确认${optName}吗?</b>`,
      nzOnOk: () => {
        const RWXIDs = [];
        this.checkIndexes.forEach((v: any) => {
          const row = this.examData[v];
          RWXIDs.push(this.examData[v].RWXID);
        });
        const ids = RWXIDs.join();
        // let user = this.userInfo.
        this.apiService.updatesgrwxPerson(ids, '', vcStatus, '', note || '', '')
          .subscribe(_res => {
            const res = JSON.parse(_res);
            if (res.type === 'success') {
              this.msg.success(optName + '成功');
              this.readyload(this.rowPage, this.pageValue);
            } else {
              this.msg.success(optName + '失败');
            }
          });
      }
    });
  }

  /**
   * 弹窗里面的提交
   */
  dataviewSubmit2(content?) {
    const saveFunc = function () {
      this.saveAllTab(this.addData, () => {
        const ids = this.addData.RWXID;
        let vcStatus;
        switch (this.pagetype) {
          case 'cjbz':
            vcStatus = '9';
            break;
          case 'gqbz':
            vcStatus = '8';
            break;
        }
        this.apiService.updatesgrwxPerson(ids, '', vcStatus, '', '', '', this.bgryArr.join('、'))
          .subscribe(_res => {
            const res = JSON.parse(_res);
            if (res.type === 'success') {
              this.msg.success('提报成功');
              this.readyload(this.rowPage, this.pageValue);
            } else {
              this.msg.error('提报失败');
            }
          });
      });
    }.bind(this);
    this.beforeSave();
    if (content) {
      this.bgryArr = [];
      this.modalService.confirm({
        nzTitle: `<i>填写把关人员</i>`,
        nzWidth: '600',
        nzContent: content,
        nzOnOk: () => {
          saveFunc();
        }
      });
    } else {
      saveFunc();
    }
  }

  /**
   * 获取作业项目//VC_PROJECT
   */
  getZyxm(RWXTYPE) {
    if (RWXTYPE) {
      this.tabCmpData.zyxmList = [];
      const url = environment.apiBase + '/csmis/jxProjects/findrwxworkpro.jwt?project=' + RWXTYPE;
      this.http.get(url).subscribe(res => {
        this.tabCmpData.zyxmList = res;
        this.tabCmpData.zyxmList.unshift({
          opValue: '',
          opName: '请选择',
        });
      });
    }
  }

  export() {
    const RWXIDs = [];
    this.checkIndexes.forEach((v: any) => {
      RWXIDs.push(this.examData[v].RWXID);
    });
    if (RWXIDs.length > 1) {
      this.msg.error('导出时只能勾选一个条目');
      return;
    }
    const ID = RWXIDs[0];
    const rows = this.examData.filter(row => row.RWXID == ID);
    const nIds = [];
    rows.forEach(_row => {
      if (ID && _row.N_ID) {
        const url = environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxpgdexport.jwt';
        this.exportFile.getDown(environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxpgdexport.jwt?ids=' + ID + '&staid=' + _row.N_ID, '维修作业派工单' + this.datePipe.transform(new Date(), 'yyyy-MM-dd') + '.xls');
      }
    });
  }

  onPeopleNodeClick(_node) {
    const node = _node.node;
    this.lastPeopleNode = node;

  }


  onPeopleChange_single(v, i, name) {
    if (!this.lastPeopleNode.isLeaf) {
      this.msg.error('请选择人员');
      setTimeout(() => {
        this.addData[i - 1][name] = '';
      }, 500);
    }
  }

  onPeopleChange(v, i) {
    const copy = JSON.parse(JSON.stringify(v));
    if (!this.lastPeopleNode.isLeaf) {
      this.msg.error('请选择人员');
      this.addData[i - 1]._vcTeammen = copy.filter(id => id != this.lastPeopleNode.key);
    }
  }

  bgryChange(v) {
    this.bgryList_filter = v ? this.bgryList.filter(el => el.opName.includes(v)) : this.bgryList;
  }

  getCj() {
    this.apiService.getAllChejian('1').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      // let delIndex;
      // for (let i = 0; i < _data.length; i++) {
      //     const el = _data[i];
      //     if (!el.opValue) {
      //         delIndex = i;
      //     }
      // }
      // _data.splice(delIndex, 1);
      this.queryData.cjList = _data;
    });
  }

  getGq(cjId) {
    if (!cjId) {
      return;
    }
    this.apiService.getgongquByCjId(cjId).subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      this.queryData.gqList = _data;
    });
  }

  getCz(gqId) {
    if (!gqId) {
      return;
    }
    this.apiService.getStationByOrgId(gqId, '1').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      this.queryData.czList = _data;
    });
  }

  onChangeCj(e) {
    this.getGq(e);
  }

  onChangeGq(e) {
    this.getCz(e);
    // this.getPeople(e);
  }

  summaryOk() {
    this.saveAllTab(this.addData, () => {
      // this.dataviewSubmit();
    });
  }

  summaryCancel() {
    this.summaryVisible = false;
  }

  switch_swfwy(index) {
    this.swfwy_isNormal[index] = !this.swfwy_isNormal[index];
  }

  zyxmClick(data, i) {
    if (!data) {
      return;
    }
    const url = environment.project + '/proThreedefense/query/' + data;
    this.http.get(url).subscribe(res => {
      const data = res.data[0];
      if (data) {
        this.addData[i].vcRiskControl = data.riskwarn || '';
        this.addData[i].vcDingkongRequire = data.prevention || '';
      }
    });
  }

  sanfangClick(e, content, index) {
    this.lastSanfangIndex = index;
    if (!this.messageIndexArr[this.lastSanfangIndex]) {
      this.messageIndexArr[this.lastSanfangIndex] = 0;
    }
    this.modalService.create({
      nzTitle: '三防',
      nzWidth: '80vw',
      nzContent: content,
      nzOnOk: () => { }
    });
  }
}
